---@class components
---@field mod_pono_diving component_mod_pono_diving

local function on_isdiving(self, value)
    if self.inst.replica.mod_pono_diving then
        self.inst.replica.mod_pono_diving:SetIsDiving(value)
    end
    
    if value then
        -- 进入潜水状态
        self.inst:AddTag("pono_is_diving")
    else
        -- 退出潜水状态
        self.inst:RemoveTag("pono_is_diving")
    end
end

---@class component_mod_pono_diving
---@field inst ent
---@field isdiving boolean 是否在潜水中
---@field pond ent 当前潜入的池塘
---@field moisture_lock_task any 雨露值锁定任务（周期任务）
---@field entry_x number 跃入时的X坐标
---@field entry_y number 跃入时的Y坐标
---@field entry_z number 跃入时的Z坐标
---@field entry_angle number 跃入时的朝向角度
---@field pond_type string 当前池塘类型
---@field health_sanity_task any 湖泊回血回理智任务
---@field dive_time number 潜水时长(秒)
---@field dive_time_task any 潜水时长计时任务
---@field damage_task any 扣血任务
---@field damage_delay_task any 12秒延迟开始扣血的任务
---@field drown_task any 溺水任务
---@field hotspring_overtime number 温泉超时时长
---@field has_drowned boolean 是否触发了溺水（用于阻止掉落物）
local mod_pono_diving = Class(

---@param self component_mod_pono_diving
---@param inst ent
function(self, inst)
    self.inst = inst
    self.isdiving = false  -- 是否在潜水中
    self.pond = nil  -- 当前潜入的池塘
    self.moisture_lock_task = nil  -- 雨露值锁定任务
    self.entry_x = nil  -- 跃入时的X坐标
    self.entry_y = nil  -- 跃入时的Y坐标
    self.entry_z = nil  -- 跃入时的Z坐标
    self.entry_angle = nil  -- 跃入时的朝向角度
    self.pond_type = nil  -- 当前池塘类型
    self.health_sanity_task = nil  -- 湖泊回血回理智任务
    self.dive_time = 0  -- 潜水时长
    self.dive_time_task = nil  -- 潜水时长计时任务
    self.damage_task = nil  -- 扣血任务
    self.damage_delay_task = nil  -- 12秒延迟开始扣血的任务
    self.drown_task = nil  -- 溺水任务
    self.hotspring_overtime = 0  -- 温泉超时时长
    
    -- 监听角色死亡事件
    inst:ListenForEvent("death", function()
        self:OnDeath()
    end)
end,
nil,
{
    isdiving = on_isdiving,
})

-- 进入池塘
function mod_pono_diving:DiveIntoPond(pond)
    if self.isdiving or not pond then
        return false
    end
    
    local inst = self.inst
    
    -- 检查是否为沼泽池塘，如果是则拒绝跃入
    if pond.prefab == "pond_mos" then
        -- 说出拒绝台词
        if inst.components.talker then
            inst.components.talker:Say("好脏，打死我都不进去...")
        end
        
        -- 播放拒绝动作（延迟一点以避免被打断）
        inst:DoTaskInTime(0.1, function()
            if inst.sg and inst.sg:HasStateTag("idle") then
                inst.sg:GoToState("emoteXL_waving2")  -- 使用摆手表情动作
            end
        end)
        
        return true  -- 返回true让动作系统认为成功，避免"我做不到"提示
    end
    
    -- 检查温泉是否使用了沐浴球（月圆结晶）
    if pond.prefab == "hotspring" then
        -- 只检查是否使用了沐浴球（不检查exothermic）
        local is_bathbombed = pond.components.bathbombable and pond.components.bathbombable.is_bathbombed
        
        if is_bathbombed then
            -- 说出拒绝台词
            if inst.components.talker then
                inst.components.talker:Say("太烫了喵...")
            end
            
            -- 播放拒绝动作（延迟一点以避免被打断）
            inst:DoTaskInTime(0.1, function()
                if inst.sg and inst.sg:HasStateTag("idle") then
                    inst.sg:GoToState("emoteXL_waving2")  -- 使用摆手表情动作
                end
            end)
            
            return true  -- 返回true让动作系统认为成功，避免"我做不到"提示
        end
    end
    
    -- 立即标记状态，防止重复点击
    self.isdiving = true
    self.pond = pond
    self.pond_type = pond.prefab  -- 记录池塘类型
    self.has_drowned = false  -- 重置溺水标记
    
    -- 标记池塘为被占用
    pond:AddTag("pono_pond_occupied")
    ---@diagnostic disable-next-line: inject-field
    pond._pono_diver = inst
    
    -- 添加潜水中的标签
    inst:AddTag("pono_in_pond")
    
    -- 触发潜水状态改变事件
    inst:PushEvent("diving_state_changed", {is_diving = true})
    
    -- 保存池塘的原始碰撞掩码
    ---@diagnostic disable-next-line: inject-field
    pond._pono_original_collision_mask = pond.Physics and pond.Physics:GetCollisionMask() or nil
    
    -- 获取池塘位置和角色当前位置
    local px, py, pz = pond.Transform:GetWorldPosition()
    local ix, iy, iz = inst.Transform:GetWorldPosition()
    
    -- 保存跃入时的位置和朝向（用于大型湖泊跃出时返回）
    self.entry_x = ix
    self.entry_y = iy
    self.entry_z = iz
    self.entry_angle = inst.Transform:GetRotation()
    
    -- 计算移动方向
    local dx = px - ix
    local dz = pz - iz
    local dist = math.sqrt(dx * dx + dz * dz)
    
    -- 先清除池塘碰撞，让角色可以穿过
    if pond.Physics then
        pond.Physics:ClearCollisionMask()
        pond.Physics:SetActive(false)
    end
    
    -- 播放跳入虫洞动画
    if inst.sg then
        inst.sg:GoToState("jumpin", {teleporter = pond, x = px, y = py, z = pz})
    end
    
    -- 生成跃入水花特效
    inst:DoTaskInTime(0.3, function()
        if pond and pond:IsValid() then
            local splash_fx = SpawnPrefab("splash_water_drop")
            if splash_fx then
                splash_fx.Transform:SetPosition(px, py, pz)
            end
        end
    end)
    
    -- 使用 Transform 逐帧移动到池塘中心
    if dist > 0.1 then
        local move_time = 0.5  -- 移动持续时间
        local update_interval = 0.033  -- 约30fps的更新频率
        local total_steps = math.floor(move_time / update_interval)
        local step_x = dx / total_steps
        local step_z = dz / total_steps
        local current_step = 0
        
        -- 使用 DoPeriodicTask 逐帧移动
        ---@diagnostic disable-next-line: inject-field
        inst._diving_move_task = inst:DoPeriodicTask(update_interval, function()
            if not self.isdiving or not inst:IsValid() then
                if inst._diving_move_task then
                    ---@diagnostic disable-next-line: undefined-field
                    inst._diving_move_task:Cancel()
                    ---@diagnostic disable-next-line: inject-field
                    inst._diving_move_task = nil
                end
                return
            end
            
            current_step = current_step + 1
            if current_step <= total_steps then
                local current_x, current_y, current_z = inst.Transform:GetWorldPosition()
                inst.Transform:SetPosition(current_x + step_x, current_y, current_z + step_z)
            else
                -- 移动完成，取消任务
                if inst._diving_move_task then
                    ---@diagnostic disable-next-line: undefined-field
                    inst._diving_move_task:Cancel()
                    ---@diagnostic disable-next-line: inject-field
                    inst._diving_move_task = nil
                end
            end
        end)
    end
    
    -- 0.5秒后清除角色碰撞
    inst:DoTaskInTime(0.5, function()
        if not self.isdiving then return end
        
        -- 取消移动任务（如果还在运行）
        if inst._diving_move_task then
            ---@diagnostic disable-next-line: undefined-field
            inst._diving_move_task:Cancel()
            ---@diagnostic disable-next-line: inject-field
            inst._diving_move_task = nil
        end
        
        -- 清除角色碰撞
        if inst.Physics then
            inst.Physics:ClearCollisionMask()
            inst.Physics:SetActive(false)
        end
        
        -- 确保角色在池塘中心
        if pond and pond:IsValid() then
            local final_px, final_py, final_pz = pond.Transform:GetWorldPosition()
            inst.Transform:SetPosition(final_px, final_py, final_pz)
        end
    end)
    
    -- 播放落水音效
    inst:DoTaskInTime(0.5, function()
        if inst.SoundEmitter then
            inst.SoundEmitter:PlaySound("dontstarve/creatures/pengull/splash")
        end
    end)
    
    -- 延迟隐藏角色和应用效果
    inst:DoTaskInTime(0.7, function()
        if not self.isdiving then return end
        
        -- 恢复池塘碰撞
        if pond and pond:IsValid() and pond.Physics then
            pond.Physics:SetActive(true)
            -- 恢复池塘的原始碰撞掩码
            ---@diagnostic disable-next-line: undefined-field
            if pond._pono_original_collision_mask then
                ---@diagnostic disable-next-line: undefined-field
                pond.Physics:SetCollisionMask(pond._pono_original_collision_mask)
                ---@diagnostic disable-next-line: inject-field
                pond._pono_original_collision_mask = nil
            end
        end
        
        -- 隐藏角色
        if inst.Hide then
            inst:Hide()
        end
        
        -- 在客户端创建潜水光源（只有自己能看见）
        if not TheWorld.ismastersim then
            if not inst._pono_diving_light then
                ---@diagnostic disable-next-line: inject-field
                inst._pono_diving_light = SpawnPrefab("mod_pono_diving_light")
                if inst._pono_diving_light then
                    ---@diagnostic disable-next-line: undefined-field
                    inst._pono_diving_light.entity:SetParent(inst.entity)
                end
            end
        end
        
        -- 隐藏手部装备（火把等有特效的物品）
        if inst.AnimState and inst.components.inventory then
            local hands_item = inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HANDS)
            if hands_item and hands_item.prefab then
                ---@diagnostic disable-next-line: inject-field
                inst._pono_saved_hand_item = hands_item
                inst.components.inventory:Unequip(EQUIPSLOTS.HANDS, true)
                inst.AnimState:ClearOverrideSymbol("swap_object")
                inst.AnimState:Hide("swap_object")
            end
        end
        
        -- 隐藏所有高亮效果
        if inst.components.highlight then
            inst.components.highlight:UnHighlight()
        end
        
        -- 遍历并隐藏特定的子实体（只隐藏光源和FX，不隐藏物品）
        for child, _ in pairs(inst.children or {}) do
            if child and child:IsValid() then
                local should_hide = false
                
                if child.prefab and (string.find(child.prefab, "light") or string.find(child.prefab, "fire")) then
                    should_hide = true
                end
                
                if child:HasTag("FX") or child:HasTag("fx") then
                    should_hide = true
                end
                
                if child.Light then
                    should_hide = true
                end
                
                if child.components and child.components.inventoryitem then
                    should_hide = false
                end
                
                if should_hide and child.Hide then
                    child:Hide()
                    ---@diagnostic disable-next-line: inject-field
                    child._pono_diving_hidden = true
                end
            end
        end
        
        -- 隐藏通过Follower绑定到symbol的特效
        ---@diagnostic disable-next-line: inject-field
        inst._pono_saved_followers = {}
        
        if inst.entity then
            for child, _ in pairs(inst.children or {}) do
                if child and child:IsValid() and child.Follower then
                    local should_hide = false
                    
                    if child.prefab then
                        local prefab_lower = string.lower(child.prefab)
                        if string.find(prefab_lower, "fire") or string.find(prefab_lower, "light") or 
                           string.find(prefab_lower, "flame") or string.find(prefab_lower, "torch") then
                            should_hide = true
                        end
                    end
                    
                    if child:HasTag("FX") or child:HasTag("fx") then
                        should_hide = true
                    end
                    
                    if child.Light then
                        should_hide = true
                    end
                    
                    if child.components and child.components.inventoryitem then
                        should_hide = false
                    end
                    
                    if should_hide and child.Hide then
                        child:Hide()
                        ---@diagnostic disable-next-line: inject-field
                        child._pono_diving_hidden = true
                        ---@diagnostic disable-next-line: undefined-field
                        table.insert(inst._pono_saved_followers, child)
                    end
                end
            end
        end
        
        -- 如果角色有光源组件，临时禁用
        if inst.Light then
            ---@diagnostic disable-next-line: inject-field
            inst._pono_saved_light_enabled = inst.Light:IsEnabled()
            inst.Light:Enable(false)
        end
        
        -- 临时移除角色的lighter组件效果
        if inst.components.lighter then
            ---@diagnostic disable-next-line: undefined-field
            local is_held = inst.components.lighter:IsBeingHeld()
            
            if is_held then
                ---@diagnostic disable-next-line: inject-field
                inst._pono_saved_lighter_held = true
                local hands_item = inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HANDS)
                inst:PushEvent("stopusingitem", {item = hands_item})
            end
        end
        
        -- 保存并移除角色身上所有的LightWatcher（这会移除所有光源效果）
        if inst.components.lightwatcher then
            ---@diagnostic disable-next-line: inject-field
            inst._pono_saved_lightwatcher = true
            -- 暂时设置光源为0，让角色认为在完全黑暗中
            if inst.LightWatcher then
                ---@diagnostic disable-next-line: inject-field
                inst._pono_saved_light_value = inst.LightWatcher:GetLightValue()
            end
        end
        
        -- 禁用角色所有装备的光源并隐藏装备的特效
        if inst.components.inventory then
            for k, item in pairs(inst.components.inventory.equipslots or {}) do
                if item and item:IsValid() then
                    if item.Light then
                        ---@diagnostic disable-next-line: inject-field
                        item._pono_saved_light_enabled = item.Light:IsEnabled()
                        item.Light:Enable(false)
                    end
                    
                    if item.children then
                        for child, _ in pairs(item.children) do
                            if child and child:IsValid() then
                                if child.Light then
                                    ---@diagnostic disable-next-line: inject-field
                                    child._pono_saved_light_enabled = child.Light:IsEnabled()
                                    child.Light:Enable(false)
                                end
                                
                                if child.Hide then
                                    child:Hide()
                                    ---@diagnostic disable-next-line: inject-field
                                    child._pono_diving_hidden = true
                                    ---@diagnostic disable-next-line: inject-field
                                    child._pono_diving_hidden_parent = item
                                end
                            end
                        end
                    end
                end
            end
        end
        
        -- 隐藏物品栏（通过添加标签，客户端监听此标签来隐藏UI）
        inst:AddTag("pono_hide_inventory")
        
        -- 【隐藏制作栏】通过标签，客户端监听
        inst:AddTag("pono_hide_crafting")
        
        -- 设置雨露值为最大并开始锁定
        if inst.components.moisture then
            inst.components.moisture:SetPercent(1)  -- 设置为最大值（100%）
            
            -- 启动雨露值锁定任务，每0.5秒检查并锁定
            ---@diagnostic disable-next-line: inject-field
            self.moisture_lock_task = inst:DoPeriodicTask(0.5, function()
                if self.isdiving and inst.components.moisture then
                    inst.components.moisture:SetPercent(1)
                end
            end)
        end
        
        -- 停止能量消耗（添加标签，能量系统会检查此标签）
        inst:AddTag("pono_energy_freeze")
        
        -- 如果是湖泊，启动回血回理智任务
        if self.pond_type == "oasislake" then
            self.health_sanity_task = inst:DoPeriodicTask(1, function()
                if self.isdiving then
                    -- 每秒恢复1点理智
                    if inst.components.sanity then
                        inst.components.sanity:DoDelta(1)
                    end
                    -- 每秒恢复0.5点血量
                    if inst.components.health then
                        inst.components.health:DoDelta(0.5, false, "lake_healing")
                    end
                end
            end)
        -- 如果是温泉，启动能量回复、理智降低和血量回复任务
        elseif self.pond_type == "hotspring" then
            self.health_sanity_task = inst:DoPeriodicTask(1, function()
                if self.isdiving then
                    -- 每秒恢复1点能量，上限125
                    if inst.components.mod_pono_energy then
                        local current = inst.components.mod_pono_energy:GetVal()
                        if current < 124 then
                            inst.components.mod_pono_energy:DoDelta(1)
                        end
                    end
                    -- 每秒降低1点理智
                    if inst.components.sanity then
                        inst.components.sanity:DoDelta(-3)
                    end
                    -- 每秒恢复2点血量
                    if inst.components.health then
                        inst.components.health:DoDelta(2, false, "hotspring_healing")
                    end
                end
            end)
        end
        
        -- 清除怪物仇恨
        if inst.components.combat then
            inst.components.combat:DropTarget()
        end
        
        -- 2秒后允许跃出
        inst:DoTaskInTime(2, function()
            if self.isdiving then
                inst:AddTag("pono_can_dive_out")
            end
        end)
        
        -- 【潜水时间限制系统】
        self.dive_time = 0
        self.hotspring_overtime = 0
        
        -- 启动潜水时长计时器（每秒累积）
        self.dive_time_task = inst:DoPeriodicTask(1, function()
            if self.isdiving then
                self.dive_time = self.dive_time + 1
            end
        end)
        
        -- 根据池塘类型设置不同的限制
        if self.pond_type == "oasislake" then
            -- 湖泊：20秒溺水，不扣血
            self.drown_task = inst:DoTaskInTime(20, function()
                if self.isdiving then
                    self:TriggerDrown()
                end
            end)
            
        elseif self.pond_type == "hotspring" then
            -- 温泉：20秒后开始计算超时，40秒强制跃出
            -- 20秒后开始计算超时时长
            inst:DoTaskInTime(20, function()
                if self.isdiving then
                    -- 启动计时器，每秒增加超时时长
                    self.damage_task = inst:DoPeriodicTask(1, function()
                        if self.isdiving then
                            self.hotspring_overtime = self.hotspring_overtime + 1
                        end
                    end)
                end
            end)
            
            -- 40秒强制跃出
            self.drown_task = inst:DoTaskInTime(40, function()
                if self.isdiving then
                    self:DiveOutOfPond()
                end
            end)
            
        else
            -- 普通池塘：12秒开始扣血(每秒2点)，20秒溺水
            -- 12秒后开始扣血
            self.damage_delay_task = inst:DoTaskInTime(12, function()
                if self.isdiving then
                    self.damage_task = inst:DoPeriodicTask(1, function()
                        if self.isdiving and inst.components.health then
                            inst.components.health:DoDelta(-2, false, "drowning")
                        end
                    end)
                end
            end)
            
            -- 20秒溺水
            self.drown_task = inst:DoTaskInTime(20, function()
                if self.isdiving then
                    self:TriggerDrown()
                end
            end)
        end
    end)
    
    return true
end

-- 从池塘中出来
function mod_pono_diving:DiveOutOfPond()
    if not self.isdiving then
        return false
    end
    
    local inst = self.inst
    local pond = self.pond  -- 保存池塘实例
    local pond_type = self.pond_type  -- 保存池塘类型
    
    -- 【新功能】潜水获取鱼类/物品 - 必须在清理状态之前调用
    -- 但如果触发了溺水，则不给予奖励
    if not self.has_drowned then
        self:TryGetFishReward(pond, pond_type)
    end
    
    -- 清理状态
    self.isdiving = false
    self.pond = nil
    self.pond_type = nil
    
    -- 移除所有潜水相关标签
    inst:RemoveTag("pono_in_pond")
    inst:RemoveTag("pono_can_dive_out")
    
    -- 恢复能量消耗
    inst:RemoveTag("pono_energy_freeze")
    
    -- 跃出消耗能量
    if inst.components.mod_pono_energy then
        if pond_type == "oasislake" then
            -- 湖泊跃出消耗2点能量
            inst.components.mod_pono_energy:DoDelta(-2)
        elseif pond_type ~= "hotspring" then
            -- 普通池塘和洞穴池塘消耗8点能量，温泉不扣除
            inst.components.mod_pono_energy:DoDelta(-8)
        end
    end
    
    -- 停止雨露值锁定任务
    if self.moisture_lock_task then
        ---@diagnostic disable-next-line: undefined-field
        self.moisture_lock_task:Cancel()
        self.moisture_lock_task = nil
    end
    
    -- 停止湖泊回血回理智任务
    if self.health_sanity_task then
        ---@diagnostic disable-next-line: undefined-field
        self.health_sanity_task:Cancel()
        self.health_sanity_task = nil
    end
    
    -- 停止所有时间限制相关任务
    if self.dive_time_task then
        ---@diagnostic disable-next-line: undefined-field
        self.dive_time_task:Cancel()
        self.dive_time_task = nil
    end
    
    if self.damage_task then
        ---@diagnostic disable-next-line: undefined-field
        self.damage_task:Cancel()
        self.damage_task = nil
    end
    
    if self.damage_delay_task then
        ---@diagnostic disable-next-line: undefined-field
        self.damage_delay_task:Cancel()
        self.damage_delay_task = nil
    end
    
    if self.drown_task then
        ---@diagnostic disable-next-line: undefined-field
        self.drown_task:Cancel()
        self.drown_task = nil
    end
    
    -- 如果是温泉且有超时，添加groggy tag和效果
    if pond_type == "hotspring" and self.hotspring_overtime > 0 then
        -- 计算groggy持续时间：5秒到20秒
        local groggy_duration = math.min(20, math.max(5, self.hotspring_overtime))
        
        -- 添加 groggy 标签
        inst:AddTag("groggy")
        
        -- 添加移速减速效果
        if inst.components.locomotor then
            inst.components.locomotor:SetExternalSpeedMultiplier(inst, "pono_hotspring_groggy", 0.5)
        end
        
        -- 定时移除groggy效果
        inst:DoTaskInTime(groggy_duration, function()
            if inst:IsValid() then
                inst:RemoveTag("groggy")
                if inst.components.locomotor then
                    inst.components.locomotor:RemoveExternalSpeedMultiplier(inst, "pono_hotspring_groggy")
                end
            end
        end)
    end
    
    self.hotspring_overtime = 0
    
    -- 触发潜水状态改变事件（解除雨露值锁定）
    inst:PushEvent("diving_state_changed", {is_diving = false})
    
    -- 清除池塘占用标记
    if pond and pond:IsValid() then
        pond:RemoveTag("pono_pond_occupied")
        ---@diagnostic disable-next-line: inject-field
        pond._pono_diver = nil
        
        -- 检查是否为大型湖泊
        local is_large_pond = pond:HasTag("pono_largepond")
        
        if is_large_pond and self.entry_x and self.entry_y and self.entry_z and self.entry_angle then
            -- 大型湖泊：保持在中心位置，稍后通过动画移动到跃入位置
            local px, py, pz = pond.Transform:GetWorldPosition()
            inst.Transform:SetPosition(px, py, pz)
            
            -- 设置朝向为跃入时的相反方向（+180度）
            local exit_angle = (self.entry_angle + 180) % 360
            inst.Transform:SetRotation(exit_angle)
        else
            -- 普通池塘：将角色位置设置到池塘中心
            local px, py, pz = pond.Transform:GetWorldPosition()
            inst.Transform:SetPosition(px, py, pz)
        end
    end
    
    -- 显示角色
    if inst.Show then
        inst:Show()
    end
    
    -- 移除潜水光源
    ---@diagnostic disable-next-line: undefined-field
    if inst._pono_diving_light then
        ---@diagnostic disable-next-line: undefined-field
        if inst._pono_diving_light:IsValid() then
            ---@diagnostic disable-next-line: undefined-field
            inst._pono_diving_light:Remove()
        end
        ---@diagnostic disable-next-line: inject-field
        inst._pono_diving_light = nil
    end
    
    -- 生成跃出水花特效
    if pond and pond:IsValid() then
        local px, py, pz = pond.Transform:GetWorldPosition()
        local splash_fx = SpawnPrefab("splash_water_drop")
        if splash_fx then
            splash_fx.Transform:SetPosition(px, py, pz)
        end
    end
    
    -- 恢复手部装备
    ---@diagnostic disable-next-line: undefined-field
    if inst._pono_saved_hand_item then
        ---@diagnostic disable-next-line: undefined-field
        local hands_item = inst._pono_saved_hand_item
        if hands_item and hands_item:IsValid() then
            inst.AnimState:Show("swap_object")
            
            if inst.components.inventory then
                inst.components.inventory:Equip(hands_item)
            end
        end
        ---@diagnostic disable-next-line: inject-field
        inst._pono_saved_hand_item = nil
    end
    
    -- 遍历并恢复所有被隐藏的子实体
    -- 注意：inst.children 的键是子实体本身，值是true
    for child, _ in pairs(inst.children or {}) do
        ---@diagnostic disable-next-line: undefined-field
        if child and child:IsValid() and child._pono_diving_hidden then
            if child.Show then
                child:Show()
            end
            ---@diagnostic disable-next-line: inject-field
            child._pono_diving_hidden = nil
        end
    end
    
    -- 恢复光源
    ---@diagnostic disable-next-line: undefined-field
    if inst._pono_saved_light_enabled then
        if inst.Light then
            ---@diagnostic disable-next-line: undefined-field
            inst.Light:Enable(inst._pono_saved_light_enabled)
        end
        ---@diagnostic disable-next-line: inject-field
        inst._pono_saved_light_enabled = nil
    end
    
    -- 恢复通过Follower绑定的特效
    ---@diagnostic disable-next-line: undefined-field
    if inst._pono_saved_followers then
        ---@diagnostic disable-next-line: undefined-field
        for i, follower in ipairs(inst._pono_saved_followers) do
            if follower and follower:IsValid() then
                ---@diagnostic disable-next-line: undefined-field
                if follower._pono_diving_hidden then
                    if follower.Show then
                        follower:Show()
                    end
                    ---@diagnostic disable-next-line: inject-field
                    follower._pono_diving_hidden = nil
                end
            end
        end
        ---@diagnostic disable-next-line: inject-field
        inst._pono_saved_followers = nil
    end
    
    -- 恢复lighter效果（火把等）
    ---@diagnostic disable-next-line: undefined-field
    if inst._pono_saved_lighter_held then
        if inst.components.lighter and inst.components.inventory then
            local hands_item = inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HANDS)
            if hands_item then
                inst:PushEvent("startusingitem", {item = hands_item})
            end
        end
        ---@diagnostic disable-next-line: inject-field
        inst._pono_saved_lighter_held = nil
    end
    
    -- 恢复装备的光源和子实体
    if inst.components.inventory then
        for k, item in pairs(inst.components.inventory.equipslots or {}) do
            if item and item:IsValid() then
                -- 恢复装备的光源
                ---@diagnostic disable-next-line: undefined-field
                if item._pono_saved_light_enabled ~= nil then
                    if item.Light then
                        ---@diagnostic disable-next-line: undefined-field
                        item.Light:Enable(item._pono_saved_light_enabled)
                    end
                    ---@diagnostic disable-next-line: inject-field
                    item._pono_saved_light_enabled = nil
                end
                
                -- 恢复装备的子实体
                if item.children then
                    for child, _ in pairs(item.children) do
                        if child and child:IsValid() then
                            -- 恢复子实体的Light
                            ---@diagnostic disable-next-line: undefined-field
                            if child._pono_saved_light_enabled ~= nil then
                                if child.Light then
                                    ---@diagnostic disable-next-line: undefined-field
                                    child.Light:Enable(child._pono_saved_light_enabled)
                                end
                                ---@diagnostic disable-next-line: inject-field
                                child._pono_saved_light_enabled = nil
                            end
                            
                            -- 恢复子实体显示
                            ---@diagnostic disable-next-line: undefined-field
                            if child._pono_diving_hidden then
                                if child.Show then
                                    child:Show()
                                end
                                ---@diagnostic disable-next-line: inject-field
                                child._pono_diving_hidden = nil
                                ---@diagnostic disable-next-line: inject-field
                                child._pono_diving_hidden_parent = nil
                            end
                        end
                    end
                end
            end
        end
    end
    
    -- 显示物品栏（移除隐藏标签）
    inst:RemoveTag("pono_hide_inventory")
    
    -- 【恢复移动】
    if inst.components.locomotor then
        inst.components.locomotor:RemoveExternalSpeedMultiplier(inst, "pono_diving")
    end
    
    -- 【显示制作栏】移除隐藏标签
    inst:RemoveTag("pono_hide_crafting")
    
    -- 【恢复动作系统】
    -- PushBufferedAction hook 会通过 pono_diving_busy 标签自动恢复
    
    -- 恢复碰撞体积和碰撞掩码
    if inst.Physics then
        inst.Physics:SetActive(true)
        inst.Physics:ClearCollisionMask()
        inst.Physics:CollidesWith(COLLISION.WORLD)
        inst.Physics:CollidesWith(COLLISION.OBSTACLES)
        inst.Physics:CollidesWith(COLLISION.SMALLOBSTACLES)
        inst.Physics:CollidesWith(COLLISION.CHARACTERS)
        inst.Physics:CollidesWith(COLLISION.GIANTS)
    end
    
    -- 播放跳跃动画
    if inst.sg then
        inst.sg:GoToState("jumpout", {teleporter = pond})
    end
    
    -- 如果是大型湖泊，跃出后移动到跃入位置
    if pond and pond:IsValid() and pond:HasTag("pono_largepond") and self.entry_x and self.entry_y and self.entry_z and self.entry_angle then
        inst:DoTaskInTime(0.1, function()
            if not inst:IsValid() then return end
            
            local cx, cy, cz = inst.Transform:GetWorldPosition()
            local exit_angle = (self.entry_angle + 180) % 360
            
            -- 移动目标：跃入时的位置
            local targetx = self.entry_x
            local targetz = self.entry_z
            local move_time = 0.5
            local interval = 0.033
            local steps = math.floor(move_time / interval)
            local stepx = (targetx - cx) / steps
            local stepz = (targetz - cz) / steps
            local current = 0
            ---@diagnostic disable-next-line: inject-field
            inst._diving_exit_task = inst:DoPeriodicTask(interval, function()
                current = current + 1
                if current <= steps then
                    local x, y, z = inst.Transform:GetWorldPosition()
                    inst.Transform:SetPosition(x + stepx, y, z + stepz)
                    -- 每帧保持相反朝向
                    if inst.Transform and inst.Transform.SetRotation then
                        inst.Transform:SetRotation(exit_angle)
                    end
                else
                    if inst._diving_exit_task then
                        ---@diagnostic disable-next-line: undefined-field
                        inst._diving_exit_task:Cancel()
                        ---@diagnostic disable-next-line: inject-field
                        inst._diving_exit_task = nil
                    end
                end
            end)
        end)
    end
    
    -- 播放企鹅出水音效
    inst:DoTaskInTime(0.2, function()
        if inst.SoundEmitter then
            inst.SoundEmitter:PlaySound("dontstarve/creatures/pengull/splash")
        end
    end)
    
    return true
end

-- 处理角色死亡（在潜水状态下）
function mod_pono_diving:OnDeath()
    local inst = self.inst
    
    -- 如果不在潜水状态，直接返回
    if not self.isdiving then
        return
    end
    
    -- 保存跃入位置
    local entry_x = self.entry_x
    local entry_y = self.entry_y
    local entry_z = self.entry_z
    
    -- 清理潜水状态
    self.isdiving = false
    inst:RemoveTag("pono_in_pond")
    inst:RemoveTag("pono_can_dive_out")
    inst:RemoveTag("pono_energy_freeze")
    inst:RemoveTag("pono_hide_inventory")
    inst:RemoveTag("pono_hide_crafting")
    
    -- 移除溺水相关标签（如果正在溺水时死亡）
    inst:RemoveTag("busy")
    inst:RemoveTag("pono_drowning_busy")
    inst:RemoveTag("notarget")
    inst:RemoveTag("noattack")
    
    -- 显示角色（如果被隐藏）
    if inst.Show then
        inst:Show()
    end
    
    -- 移除潜水光源
    ---@diagnostic disable-next-line: undefined-field
    if inst._pono_diving_light then
        ---@diagnostic disable-next-line: undefined-field
        if inst._pono_diving_light:IsValid() then
            ---@diagnostic disable-next-line: undefined-field
            inst._pono_diving_light:Remove()
        end
        ---@diagnostic disable-next-line: inject-field
        inst._pono_diving_light = nil
    end
    
    -- 遍历并恢复所有被隐藏的子实体
    -- 注意：inst.children 的键是子实体本身，值是true
    for child, _ in pairs(inst.children or {}) do
        ---@diagnostic disable-next-line: undefined-field
        if child and child:IsValid() and child._pono_diving_hidden then
            if child.Show then
                child:Show()
            end
            ---@diagnostic disable-next-line: inject-field
            child._pono_diving_hidden = nil
        end
    end
    
    -- 恢复光源
    ---@diagnostic disable-next-line: undefined-field
    if inst._pono_saved_light_enabled then
        if inst.Light then
            ---@diagnostic disable-next-line: undefined-field
            inst.Light:Enable(inst._pono_saved_light_enabled)
        end
        ---@diagnostic disable-next-line: inject-field
        inst._pono_saved_light_enabled = nil
    end
    
    -- 恢复装备的光源和子实体
    if inst.components.inventory then
        for k, item in pairs(inst.components.inventory.equipslots or {}) do
            if item and item:IsValid() then
                -- 恢复装备的光源
                ---@diagnostic disable-next-line: undefined-field
                if item._pono_saved_light_enabled ~= nil then
                    if item.Light then
                        ---@diagnostic disable-next-line: undefined-field
                        item.Light:Enable(item._pono_saved_light_enabled)
                    end
                    ---@diagnostic disable-next-line: inject-field
                    item._pono_saved_light_enabled = nil
                end
                
                -- 恢复装备的子实体
                if item.children then
                    for child, _ in pairs(item.children) do
                        if child and child:IsValid() then
                            -- 恢复子实体的Light
                            ---@diagnostic disable-next-line: undefined-field
                            if child._pono_saved_light_enabled ~= nil then
                                if child.Light then
                                    ---@diagnostic disable-next-line: undefined-field
                                    child.Light:Enable(child._pono_saved_light_enabled)
                                end
                                ---@diagnostic disable-next-line: inject-field
                                child._pono_saved_light_enabled = nil
                            end
                            
                            -- 恢复子实体显示
                            ---@diagnostic disable-next-line: undefined-field
                            if child._pono_diving_hidden then
                                if child.Show then
                                    child:Show()
                                end
                                ---@diagnostic disable-next-line: inject-field
                                child._pono_diving_hidden = nil
                                ---@diagnostic disable-next-line: inject-field
                                child._pono_diving_hidden_parent = nil
                            end
                        end
                    end
                end
            end
        end
    end
    
    -- 恢复物理碰撞
    if inst.Physics then
        inst.Physics:SetActive(true)
        inst.Physics:ClearCollisionMask()
        inst.Physics:CollidesWith(COLLISION.WORLD)
        inst.Physics:CollidesWith(COLLISION.OBSTACLES)
        inst.Physics:CollidesWith(COLLISION.SMALLOBSTACLES)
        inst.Physics:CollidesWith(COLLISION.CHARACTERS)
        inst.Physics:CollidesWith(COLLISION.GIANTS)
    end
    
    -- 恢复locomotor
    if inst.components.locomotor then
        inst.components.locomotor:RemoveExternalSpeedMultiplier(inst, "pono_diving")
        inst.components.locomotor:RemoveExternalSpeedMultiplier(inst, "drowning_server")
    end
    
    -- 恢复playercontroller（如果被禁用）
    if inst.components.playercontroller then
        inst.components.playercontroller:Enable(true)
    end
    
    -- 停止所有任务
    if self.moisture_lock_task then
        self.moisture_lock_task:Cancel()
        self.moisture_lock_task = nil
    end
    if self.health_sanity_task then
        self.health_sanity_task:Cancel()
        self.health_sanity_task = nil
    end
    if self.dive_time_task then
        self.dive_time_task:Cancel()
        self.dive_time_task = nil
    end
    if self.damage_task then
        self.damage_task:Cancel()
        self.damage_task = nil
    end
    if self.damage_delay_task then
        self.damage_delay_task:Cancel()
        self.damage_delay_task = nil
    end
    if self.drown_task then
        self.drown_task:Cancel()
        self.drown_task = nil
    end
    
    -- 清理池塘占用
    if self.pond and self.pond:IsValid() then
        self.pond:RemoveTag("pono_pond_occupied")
        ---@diagnostic disable-next-line: inject-field
        self.pond._pono_diver = nil
    end
    
    self.pond = nil
    self.pond_type = nil
    self.dive_time = 0
    self.hotspring_overtime = 0
    
    -- 传送到跃入位置
    if entry_x and entry_y and entry_z then
        inst:DoTaskInTime(0, function()
            if inst:IsValid() then
                if inst.Physics then
                    inst.Physics:Teleport(entry_x, entry_y, entry_z)
                else
                    inst.Transform:SetPosition(entry_x, entry_y, entry_z)
                end
            end
        end)
    end
    
    -- 触发潜水状态改变事件
    inst:PushEvent("diving_state_changed", {is_diving = false})
end

-- 触发溺水事件
function mod_pono_diving:TriggerDrown()
    local inst = self.inst
    
    -- 标记已触发溺水，阻止掉落物
    self.has_drowned = true
    
    -- 保存跃入位置数据和池塘类型
    local drown_data = {
        entry_x = self.entry_x,
        entry_y = self.entry_y,
        entry_z = self.entry_z,
        pond_type = self.pond_type,  -- 传递池塘类型
    }
    
    -- 清理潜水状态
    if self.isdiving then
        -- 先清理潜水相关状态和任务
        self.isdiving = false
        inst:RemoveTag("pono_in_pond")
        inst:RemoveTag("pono_can_dive_out")
        inst:RemoveTag("pono_energy_freeze")
        inst:RemoveTag("pono_hide_inventory")
        inst:RemoveTag("pono_hide_crafting")
        
        -- 停止所有任务
        if self.moisture_lock_task then
            self.moisture_lock_task:Cancel()
            self.moisture_lock_task = nil
        end
        if self.health_sanity_task then
            self.health_sanity_task:Cancel()
            self.health_sanity_task = nil
        end
        if self.damage_task then
            self.damage_task:Cancel()
            self.damage_task = nil
        end
        if self.damage_delay_task then
            self.damage_delay_task:Cancel()
            self.damage_delay_task = nil
        end
        if self.drown_task then
            self.drown_task:Cancel()
            self.drown_task = nil
        end
        
        -- 清理池塘占用
        if self.pond and self.pond:IsValid() then
            self.pond:RemoveTag("pono_pond_occupied")
            self.pond._pono_diver = nil
        end
        
        self.pond = nil
        self.pond_type = nil
        
        -- 【不要立即显示角色】溺水组件会在合适的时机显示
        -- 显示角色
        -- if inst.Show then
        --     inst:Show()
        -- end
        
        -- 恢复碰撞
        if inst.Physics then
            inst.Physics:SetActive(true)
            inst.Physics:ClearCollisionMask()
            inst.Physics:CollidesWith(COLLISION.WORLD)
            inst.Physics:CollidesWith(COLLISION.OBSTACLES)
            inst.Physics:CollidesWith(COLLISION.SMALLOBSTACLES)
            inst.Physics:CollidesWith(COLLISION.CHARACTERS)
            inst.Physics:CollidesWith(COLLISION.GIANTS)
        end
        
        -- 显示物品栏和制作栏
        inst:RemoveTag("pono_hide_inventory")
        inst:RemoveTag("pono_hide_crafting")
        
        -- 恢复移动
        if inst.components.locomotor then
            inst.components.locomotor:RemoveExternalSpeedMultiplier(inst, "pono_diving")
        end
    end
    
    -- 触发溺水惩罚（通过drowning组件）
    if inst.components.mod_pono_drowning then
        inst.components.mod_pono_drowning:TriggerDrown(drown_data)
    end
end

-- 检查是否在潜水
function mod_pono_diving:IsDiving()
    return self.isdiving
end

-- 获取当前池塘
function mod_pono_diving:GetPond()
    return self.pond
end

-- 尝试获取鱼类奖励
function mod_pono_diving:TryGetFishReward(pond, pond_type)
    local inst = self.inst
    local dive_time = self.dive_time
    
    -- 只有超过3秒才有概率获得
    if dive_time < 3 then
        return
    end
    
    -- 计算获取概率：3秒30%，10秒100%，线性插值
    local fish_chance = math.min(1.0, 0.3 + (dive_time - 3) / 7 * 0.7)
    local random_value = math.random()
    
    -- 根据池塘类型给予奖励
    if pond_type == "pond" then
        -- 普通池塘：活淡水鱼
        if random_value < fish_chance then
            self:GiveFishFromPond(pond, "pondfish", pond_type)
        else
            -- 即使没有获得鱼，也有概率掉落额外物品
            inst:DoTaskInTime(0.6, function()
                if inst:IsValid() then
                    self:GiveExtraLootFromPond(pond_type)
                end
            end)
        end
    elseif pond_type == "pond_cave" then
        -- 洞穴池塘：活带鱼
        if random_value < fish_chance then
            self:GiveFishFromPond(pond, "pondeel", pond_type)
        else
            -- 即使没有获得鱼，也有概率掉落额外物品
            inst:DoTaskInTime(0.6, function()
                if inst:IsValid() then
                    self:GiveExtraLootFromPond(pond_type)
                end
            end)
        end
    elseif pond_type == "oasislake" then
        -- 湖泊：检查是否学习了沙漠护目镜
        local has_goggles = inst.components.builder and inst.components.builder:KnowsRecipe("deserthat")
        
        if not has_goggles then
            -- 没学习则必定给蓝图（延迟到跃出动画结束后掉落）
            inst:DoTaskInTime(0.6, function()
                if inst:IsValid() then
                    -- 直接生成沙漠护目镜蓝图
                    local item = SpawnPrefab("deserthat_blueprint")
                    if item then
                        local x, y, z = inst.Transform:GetWorldPosition()
                        item.Transform:SetPosition(x, y, z)
                        
                        -- 添加掉落动画
                        if item.Physics then
                            local angle = math.random() * 2 * PI
                            local speed = 2 + math.random()
                            local vx = speed * math.cos(angle)
                            local vz = speed * math.sin(angle)
                            item.Physics:SetVel(vx, 8, vz)
                        end
                    end
                end
            end)
        else
            -- 已学习则按湖泊钓鱼掉落表
            if random_value < fish_chance then
                self:GiveLakeFishingLoot(pond)
            end
        end
    elseif pond_type == "hotspring" then
        -- 温泉：必须在20秒内跃出
        if dive_time <= 20 and random_value < fish_chance then
            self:GiveHotspringLoot()
        end
    end
end

-- 从池塘获取鱼（如果池塘有鱼则减少鱼数，如果没有鱼则不给予奖励并播放台词）
-- 同时有概率额外掉落其他物品
function mod_pono_diving:GiveFishFromPond(pond, fish_prefab, pond_type)
    local inst = self.inst
    
    -- 检查池塘鱼数（使用 fishleft 字段）
    local fish_left = 0
    if pond and pond:IsValid() and pond.components.fishable then
        fish_left = pond.components.fishable.fishleft or 0
    end
    
    -- 判断是否有鱼可以捞
    local has_fish = fish_left > 0
    
    -- 如果池塘没有鱼，播放台词
    if not has_fish then
        if inst.components.talker then
            inst.components.talker:Say("池塘里没有鱼了...")
        end
    else
        -- 有鱼则减少池塘鱼数
        if pond and pond:IsValid() and pond.components.fishable then
            pond.components.fishable.fishleft = fish_left - 1
        end
    end
    
    -- 延迟到跃出动画结束后掉落物品
    inst:DoTaskInTime(0.6, function()
        if inst:IsValid() then
            -- 如果有鱼，掉落鱼类物品
            if has_fish then
                local fish = SpawnPrefab(fish_prefab)
                if fish then
                    local x, y, z = inst.Transform:GetWorldPosition()
                    fish.Transform:SetPosition(x, y, z)
                    
                    -- 添加掉落动画
                    if fish.Physics then
                        local angle = math.random() * 2 * PI
                        local speed = 2 + math.random()
                        local vx = speed * math.cos(angle)
                        local vz = speed * math.sin(angle)
                        fish.Physics:SetVel(vx, 8, vz)
                    end
                end
            end
            
            -- 额外掉落物品（无论是否有鱼）
            self:GiveExtraLootFromPond(pond_type)
        end
    end)
end

-- 从池塘额外获取物品
function mod_pono_diving:GiveExtraLootFromPond(pond_type)
    local inst = self.inst
    
    local loot_table = {}
    
    if pond_type == "pond" then
        -- 池塘额外掉落：kelp 20%，cutreeds 30%，froglegs 10%，40%无
        loot_table = {
            {item = "kelp", weight = 20},
            {item = "cutreeds", weight = 30},
            {item = "froglegs", weight = 10, freshness = 0.75},  -- 75%新鲜度
            {item = nil, weight = 40},  -- 40%无额外掉落
        }
    elseif pond_type == "pond_cave" then
        -- 洞穴池塘额外掉落：nitre 50%，batwing 20%，30%无
        loot_table = {
            {item = "nitre", weight = 50},
            {item = "batwing", weight = 20, freshness = 0.80},  -- 80%新鲜度
            {item = nil, weight = 30},  -- 30%无额外掉落
        }
    else
        return  -- 其他类型池塘不掉落
    end
    
    -- 计算总权重
    local total_weight = 0
    for _, entry in ipairs(loot_table) do
        total_weight = total_weight + entry.weight
    end
    
    -- 随机选择
    local roll = math.random() * total_weight
    local cumulative = 0
    
    for _, entry in ipairs(loot_table) do
        cumulative = cumulative + entry.weight
        if roll <= cumulative then
            if entry.item then  -- 如果不是nil（无掉落）
                local item = SpawnPrefab(entry.item)
                if item then
                    local x, y, z = inst.Transform:GetWorldPosition()
                    item.Transform:SetPosition(x, y, z)
                    
                    -- 设置新鲜度（如果是可腐烂物品）
                    if entry.freshness and item.components.perishable then
                        local max_freshness = item.components.perishable.perishremainingtime
                        item.components.perishable:SetPercent(entry.freshness)
                    end
                    
                    -- 添加掉落动画
                    if item.Physics then
                        local angle = math.random() * 2 * PI
                        local speed = 2 + math.random()
                        local vx = speed * math.cos(angle)
                        local vz = speed * math.sin(angle)
                        item.Physics:SetVel(vx, 8, vz)
                    end
                end
            end
            return
        end
    end
end

-- 给予湖泊钓鱼掉落物
function mod_pono_diving:GiveLakeFishingLoot(pond)
    local inst = self.inst
    
    -- 湖泊掉落表：80%起皱的包裹，15%活淡水鱼，5%沙之石
    local loot_table = {
        {item = "wetpouch", weight = 80, consume_fish = false},          -- 起皱的包裹 (不消耗鱼数)
        {item = "pondfish", weight = 15, consume_fish = true},           -- 活淡水鱼 (消耗鱼数)
        {item = "townportaltalisman", weight = 5, consume_fish = false}, -- 沙之石 (不消耗鱼数)
    }
    
    -- 计算总权重
    local total_weight = 0
    for _, entry in ipairs(loot_table) do
        total_weight = total_weight + entry.weight
    end
    
    -- 随机选择
    local roll = math.random() * total_weight
    local cumulative = 0
    
    for _, entry in ipairs(loot_table) do
        cumulative = cumulative + entry.weight
        if roll <= cumulative then
            -- 如果是淡水鱼，需要检查并消耗鱼数
            if entry.consume_fish then
                -- 检查池塘鱼数
                local fish_left = 0
                if pond and pond:IsValid() and pond.components.fishable then
                    fish_left = pond.components.fishable.fishleft or 0
                end
                
                -- 如果池塘没有鱼，播放台词并返回
                if fish_left <= 0 then
                    if inst.components.talker then
                        inst.components.talker:Say("湖里没有鱼了...")
                    end
                    return
                end
                
                -- 减少池塘鱼数
                if pond and pond:IsValid() and pond.components.fishable then
                    pond.components.fishable.fishleft = fish_left - 1
                end
            end
            
            -- 延迟到跃出动画结束后掉落物品
            inst:DoTaskInTime(0.6, function()
                if inst:IsValid() then
                    local item = SpawnPrefab(entry.item)
                    if item then
                        local x, y, z = inst.Transform:GetWorldPosition()
                        item.Transform:SetPosition(x, y, z)
                        
                        -- 添加掉落动画
                        if item.Physics then
                            local angle = math.random() * 2 * PI
                            local speed = 2 + math.random()
                            local vx = speed * math.cos(angle)
                            local vz = speed * math.sin(angle)
                            item.Physics:SetVel(vx, 8, vz)
                        end
                    end
                end
            end)
            return
        end
    end
end

-- 给予温泉掉落物
function mod_pono_diving:GiveHotspringLoot()
    local inst = self.inst
    
    -- 温泉掉落表：硝石30%、浮木30%、月岩15%、火龙果种子10%、红宝石10%、蓝宝石10%、月亮碎片5%
    local loot_table = {
        {item = "nitre", weight = 30},             -- 硝石 30%
        {item = "driftwood_log", weight = 30},     -- 浮木 30%
        {item = "moonrocknugget", weight = 15},    -- 月岩 15%
        {item = "dragonfruit_seeds", weight = 10}, -- 火龙果种子 10%
        {item = "redgem", weight = 5},            -- 红宝石 5%
        {item = "bluegem", weight = 5},           -- 蓝宝石 5%
        {item = "moon_tear", weight = 5},          -- 月亮碎片 5%
    }
    
    -- 计算总权重
    local total_weight = 0
    for _, entry in ipairs(loot_table) do
        total_weight = total_weight + entry.weight
    end
    
    -- 随机选择
    local roll = math.random() * total_weight
    local cumulative = 0
    
    for _, entry in ipairs(loot_table) do
        cumulative = cumulative + entry.weight
        if roll <= cumulative then
            -- 延迟到跃出动画结束后掉落物品
            inst:DoTaskInTime(0.6, function()
                if inst:IsValid() then
                    local item = SpawnPrefab(entry.item)
                    if item then
                        local x, y, z = inst.Transform:GetWorldPosition()
                        item.Transform:SetPosition(x, y, z)
                        
                        -- 添加掉落动画
                        if item.Physics then
                            local angle = math.random() * 2 * PI
                            local speed = 2 + math.random()
                            local vx = speed * math.cos(angle)
                            local vz = speed * math.sin(angle)
                            item.Physics:SetVel(vx, 8, vz)
                        end
                    end
                end
            end)
            return
        end
    end
end

function mod_pono_diving:OnSave()
    return {
        isdiving = self.isdiving,
    }
end

function mod_pono_diving:OnLoad(data)
    if data then
        -- 注意：池塘引用不保存，重新加载后需要重置状态
        if data.isdiving then
            -- 强制退出潜水状态（防止存档时在池塘中导致的问题）
            self.isdiving = false
            self.pond = nil
        end
    end
end

return mod_pono_diving